//
//  CloudDepartmentResultController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/26.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

class CloudDepartmentResultController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .background
    }
    
    private var viewModel: DepartmentViewModel? {
        didSet {
            tableView.reloadData()
        }
    }

    @IBOutlet private var activityView: UIActivityIndicatorView!

    @IBOutlet private var tableView: UITableView! {
        didSet {
            tableView.contentInset = UIEdgeInsets(top: 40, left: 0, bottom: 0, right: 0)
            tableView.rowHeight = 70
            tableView.estimatedRowHeight = UITableView.automaticDimension
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.register(CloudDepartmentCell.nibForCell(),
                               forCellReuseIdentifier: CloudDepartmentCell.reuseIdentifier())
        }
    }

}

extension CloudDepartmentResultController {
    func loadData(department: String = "") {
        activityView.startAnimating()
        DepartmentViewModel.getDepartmentList(department: department, success: { models in
            self.activityView.stopAnimating()
            self.viewModel = DepartmentViewModel(models: models)
        }) { errorMsg in
            self.activityView.stopAnimating()
            HUDTool.showError(message: errorMsg)
        }
    }
}

// MARK: - DataSource & Delegate
extension CloudDepartmentResultController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.numberOfRows ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CloudDepartmentCell.reuseIdentifier(),
                                                 for: indexPath) as! CloudDepartmentCell
        if let vm = viewModel?.viewModel(for: indexPath) {
            cell.configure(with: vm)
        }
        return cell
    }
}

extension CloudDepartmentResultController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        guard let vm = viewModel?.viewModel(for: indexPath) else { return }
        pushDoctorReserveVc(with: vm)
    }
}

private extension CloudDepartmentResultController {
    func pushDoctorReserveVc(with vm: DepartmentViewModel.RowViewModel) {
//        let reserveVc = CloudDoctorReserveController(with: vm.departmentId)
//        presentingViewController?.navigationController?.pushViewController(reserveVc, animated: true)
    }
}
